/*
 * LastComeFirstServed.java 13.06.2013
 *
 * Copyright (c) 2013 1&1 Internet AG. All rights reserved.
 *
 * $Id$
 */
package de.tum.wi.som.prio.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.tum.wi.som.Node;
import de.tum.wi.som.Project;
import de.tum.wi.som.prio.PriorityRule;
import de.tum.wi.som.util.PrioUtil;

/**
 * Max(ESi)
 *
 * @author epollok
 *
 */
public class LastComeFirstServed implements PriorityRule {

    @Override
    public void prioritize(Project project) {
        project.calcProjectGraph();
        List<Node> remainingNodes = new ArrayList<Node>();
        remainingNodes.addAll(Arrays.asList(project.getNodes()));
        List<Node> scheduledNodes = new ArrayList<Node>();
        List<Node> accessibleNodes;
        Node dummyNode = new Node(0, new int[0]);
        while (!remainingNodes.isEmpty()) {
            accessibleNodes = PrioUtil.determineAccesibleNodes(scheduledNodes, project.getSource(), remainingNodes);
            if (accessibleNodes.size() == 0) {
            	System.err.println("No accessible nodes found in LastComeFirstServe");
            	return;
            }

            // prioritize accesible nodes
            Node candidateNode = dummyNode;
            double maxEs = 0;
            for (Node node : accessibleNodes) {
                if (candidateNode == dummyNode || node.getEarliestStart() > maxEs) {
                    candidateNode = node;
                    maxEs = node.getEarliestStart();
                }
            }
            remainingNodes.remove(candidateNode);
            scheduledNodes.add(candidateNode);
        }
        project.setNodes(scheduledNodes.toArray(new Node[scheduledNodes.size()]));
    }
    
    @Override
	public String toString(){
		return "LastComeFirstServe";
	}
}
